package com.mishow.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.fragment.IndexFragment;
import com.mishow.fragment.MessageFragment;
import com.mishow.fragment.MyFragment;
import com.mishow.fragment.StarFragment;
import com.mishow.fragment.base.BaseFragment;
import com.mishow.log.MyLog;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.PushManagerUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.widget.SelectPicPopupWindow;
import com.mishow.widget.SelectPicPopupWindow.PopupDismissListener;
/**
 * 
 * 作者：wei.miao <br/>
 * 描述：首页框架界面
 */
public class MainActivity extends BaseActivity implements PopupDismissListener{
	
	private LinearLayout tab_item;
	
	private RadioGroup rg_group;
	/** 首页**/
	private RadioButton rb_index;
	/** 星秀 **/
	private RadioButton rb_star;
	
	/** 发布 **/
	private RadioButton rb_publish;
	
	/** 消息 **/
	private RadioButton rb_msg;
	/** 我的  **/
	private RadioButton rb_my;
	
	/** 红点 **/
	private ImageView image_message_point;

	/** fm对象 **/
	private static FragmentManager fragmentManager;
	
	private IndexFragment indexFragment;
	
	private StarFragment starFragment;
	
	private MessageFragment messageFragment;
	
	private MyFragment myFragment;
	/** 按第一次返回键的时间 **/
	private long touchTime = 0l;
	/** 两次返回键的有效时间 **/
	private long waitTime = 2000l;
	
	private SharedPreferencesUtil mShPreferencesUtil;
	
	/**
     * 广播接收器
     */
    private MyReceiver myReceiver;
	
	public static void intoActivity(Context context){
		Intent intent = new Intent(context,MainActivity.class);
		context.startActivity(intent);
	}
	
	@Override
	protected void initData() {
		
		mShPreferencesUtil = new SharedPreferencesUtil(mContext);
		fragmentManager = getSupportFragmentManager();
		
		initReceiver();
	}

	@Override
	protected void initView(Bundle savedInstanceState) {
		
		setContentView(R.layout.activity_main);
		
		tab_item = (LinearLayout)findViewById(R.id.tab_item);
		rg_group = (RadioGroup)findViewById(R.id.rg_group);
		rb_index = (RadioButton)findViewById(R.id.rb_index);
		rb_star = (RadioButton)findViewById(R.id.rb_star);
		
		rb_publish = (RadioButton)findViewById(R.id.rb_publish);
		
		rb_msg = (RadioButton)findViewById(R.id.rb_msg);
		rb_my = (RadioButton)findViewById(R.id.rb_my);
		
		image_message_point = (ImageView)findViewById(R.id.image_message_point);
	}

	@Override
	protected void setAttribute() {
		
		rg_group.setOnCheckedChangeListener(onChecked);
		rb_publish.setOnClickListener(onClickListener);
		if (indexFragment == null) {
			
			indexFragment = IndexFragment.newInstance();
		}
		showFragment(indexFragment);
		showTabColors();
	}
	
	@Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        //handExtraData();
        super.onNewIntent(intent);
    }
	
	SelectPicPopupWindow menuWindow; 
	
	private void getPop(){
		
		 menuWindow = new SelectPicPopupWindow(MainActivity.this,onClickListener,this);
		 //menuWindow.setBackgroundDrawable(new BitmapDrawable(getResources().getResourceName(R.drawable.pop_corne)));
         //这个地方必须要加，否则背景为黑色
		 menuWindow.setBackgroundDrawable(new BitmapDrawable());
		 //显示窗口 //设置layout在PopupWindow中显示的位置 
         menuWindow.showAtLocation(tab_item, Gravity.TOP, 0,0);  
         
         rb_publish.startAnimation(createHintSwitchAnimation(false));
	}
	
	/**
	 *选择状态
	 */
	private  OnCheckedChangeListener onChecked = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			switch (checkedId) {
			case R.id.rb_index:
				if (indexFragment == null) {
					
					indexFragment = IndexFragment.newInstance();
				}
				showFragment(indexFragment);
				break;
			case R.id.rb_star:
				if (starFragment == null) {
					
					starFragment = StarFragment.newInstance();
				}
				showFragment(starFragment);
				break;
			case R.id.rb_msg:
				//判断是否登录
				if (!mShPreferencesUtil.getLoginState()) {
                    
                    LoginActivity.intoActivity(mContext,Constants.LOGIN_REQUEST_CODE,Constants.MAIN_MSG_TAB);
                    
                } else {
                	if (messageFragment == null) {
    					
    					messageFragment = MessageFragment.newInstance();
    				}
    				showFragment(messageFragment);
                }
				break;
			case R.id.rb_my:
				//判断是否登录
				if (!mShPreferencesUtil.getLoginState()) {
                    
                    LoginActivity.intoActivity(mContext,Constants.LOGIN_REQUEST_CODE,Constants.MAIN_MY_TAB);
                    
                } else {
                	if (myFragment == null) {
    					
    					myFragment = MyFragment.newInstance();
    				}
    				showFragment(myFragment);
                }
				
				break;
			}
			showTabColors();
		}
	};
	
	public void setMessageChecked(){
		rb_msg.setChecked(true);
	}
	
	public void setMyChecked(){
		rb_my.setChecked(true);
	}
	
	
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.rb_publish://发布
				getPop();
				getFragmentTag();
				break;
			case R.id.btn_main_dynamic:
				ToastUtil.show(mContext, "动态");
				//判断是否登录
				if (!mShPreferencesUtil.getLoginState()) {
                    //LoginActivity.intoActivity(mContext,Constants.LOGIN_REQUEST_CODE);
                }else{
                	menuWindow.dismiss();
    				DynamicReleaseActivity.intoActivity(mContext);
                }
				break;
			case R.id.btn_main_annunciate:
				ToastUtil.show(mContext, "通告");
				//判断是否登录
				if (!mShPreferencesUtil.getLoginState()) {
                    //LoginActivity.intoActivity(mContext,Constants.LOGIN_REQUEST_CODE);
                }else{
                	menuWindow.dismiss();
    				AnnunciateReleaseActivity.intoActivity(mContext);
                }
				break;
			case R.id.btn_main_selection:
				ToastUtil.show(mContext, "精选");
				//判断是否登录
				if (!mShPreferencesUtil.getLoginState()) {
                    //LoginActivity.intoActivity(mContext,Constants.LOGIN_REQUEST_CODE);
                }else{
                	menuWindow.dismiss();
    				SelectReleaseActivity.intoActivity(mContext);
                }
				break;
			}
			
		}
	};
	
	/**
	 * 标识当前选中状态
	 */
	public void getFragmentTag(){
		
		if (fragmentManager.findFragmentByTag("fragmentTag") == indexFragment ) {
			
			rb_index.setChecked(true);
			
		}else if (fragmentManager.findFragmentByTag("fragmentTag") == starFragment) {
			
			rb_star.setChecked(true);
			
		}else if (fragmentManager.findFragmentByTag("fragmentTag") == messageFragment) {
			
			rb_msg.setChecked(true);
			
		}else{
			
			rb_my.setChecked(true);
		}
	}
	/**
	 * 显示fragment列表
	 */
	public void showFragment(BaseFragment fragment) {
		//FragmentTransaction事务被用来添加、移除、附加、分离或替换fragment队列中的fragment
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		transaction.replace(R.id.tab_content, fragment,"fragmentTag");
		transaction.commit();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			
			// 如果当前不是在首页则，先返回首页
			if (fragmentManager.findFragmentByTag("fragmentTag") != indexFragment) {
				BaseFragment baseFragment = (BaseFragment) fragmentManager.findFragmentById(R.id.tab_content);
				if (!baseFragment.onBackPress()) {// 判断Fragment中是否消费返回事件
					showFragment(indexFragment);
					rb_index.setChecked(true);
				}
				return true;
			}
			

			// 实现按两次“返回键”按退出程序
			long currentTime = System.currentTimeMillis();
			if (currentTime - touchTime > waitTime) {
				// Toast提示再次点击
				Toast.makeText(MainActivity.this, getResources().getString(R.string.click_again_exit),
						Toast.LENGTH_SHORT).show();
				touchTime = currentTime;// 记录第一次点击的时间
			} else {
				this.finish();
			}
			return true;
		}
		return false;
	
	}
	
	/**
	 *  tab字体颜色显示
	 */
	public void showTabColors(){
		
		if(rb_index.isChecked()){
			rb_index.setTextColor(getResources().getColor(R.color.rb_select));
		}else{
			rb_index.setTextColor(getResources().getColor(R.color.rb_unselect));
		}
		if(rb_star.isChecked()){
			rb_star.setTextColor(getResources().getColor(R.color.rb_select));
		}else{
			rb_star.setTextColor(getResources().getColor(R.color.rb_unselect));
		}
		if(rb_msg.isChecked()){
			rb_msg.setTextColor(getResources().getColor(R.color.rb_select));
		}else{
			rb_msg.setTextColor(getResources().getColor(R.color.rb_unselect));
		}
		if(rb_my.isChecked()){
			rb_my.setTextColor(getResources().getColor(R.color.rb_select));
		}else{
			rb_my.setTextColor(getResources().getColor(R.color.rb_unselect));
		}
	}

	@Override
	public void dismissListener() {
		
		//rb_publish.setBackgroundResource(R.drawable.icon_fabu_default);
		rb_publish.startAnimation(createHintSwitchAnimation(true));
	}
	
	private Animation createHintSwitchAnimation(final boolean expanded) {
		//loat fromDegrees：旋转的开始角度。 
		//float toDegrees：旋转的结束角度。 
		//int pivotXType：X轴的伸缩模式，可以取值为ABSOLUTE(绝对)、RELATIVE_TO_SELF(相对于自己)、RELATIVE_TO_PARENT(相对于父控件) 
		//float pivotXValue：X坐标的伸缩值。 
		//int pivotYType：Y轴的伸缩模式，可以取值为ABSOLUTE、RELATIVE_TO_SELF、RELATIVE_TO_PARENT。 
		//float pivotYValue：Y坐标的伸缩值。 
		float pivotX = 0.5f; // 取自身区域在X轴上的中心点
		float pivotY = 0.5f; // 取自身区域在Y轴上的中心点
        Animation animation = new RotateAnimation(expanded ? 90 : 0, expanded ? 0 : 90, Animation.RELATIVE_TO_SELF,
        		pivotX, Animation.RELATIVE_TO_SELF, pivotY);
        
        //执行前的等待时间 
        animation.setStartOffset(0);
        //设置动画持续时间 
        animation.setDuration(500);
        animation.setInterpolator(new DecelerateInterpolator());
        //动画执行完后是否停留在执行完的状态 
        animation.setFillAfter(true);
 
        return animation;
    } 
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case Constants.LOGIN_REQUEST_CODE:
				MyLog.d("onRestart===onActivityResult===");
				if (intent != null && intent.getExtras() != null) {
					int currentTabIndex = (int)intent.getExtras().get(Constants.LOGIN_RESPONSE_NAME);
					if (currentTabIndex == Constants.MAIN_MSG_TAB) {
						/*if (messageFragment == null) {
	    					
	    					messageFragment = MessageFragment.newInstance();
	    				}
	    				showFragment(messageFragment);*/
						//setMessageChecked();
						
	                } else if (currentTabIndex == Constants.MAIN_MY_TAB) {
	                	/*if (myFragment == null) {
	    					
	                		myFragment = MyFragment.newInstance();
	    				}
	    				showFragment(myFragment);*/
	                	//setMyChecked();
	                }
	                // 登录成功检查是否有新消息
	                //getMineNewFromServer();
				}
				break;
			default:
				break;
			}
		}
		 super.onActivityResult(requestCode, resultCode, intent);
	}

	
	@Override
	protected void onRestart() {
		super.onRestart();
		MyLog.d("onRestart======");
		getFragmentTag();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 广播接收器解除注册
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
	}
	
	/**
     * 初始化广播接收器
     */
    private void initReceiver() {
        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(PushManagerUtil.ACTION_MINE_NEW);
        filter.setPriority(3);
        registerReceiver(myReceiver, filter);
    }
	
	/**
     * 广播接收器：用于处理首页消息红点显示
     */
    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String actionStr = intent.getAction();
            if (PushManagerUtil.ACTION_MINE_NEW.equals(actionStr)) {
               
            	if (fragmentManager.findFragmentByTag("fragmentTag")  == messageFragment) {
                    Fragment fragment = fragmentManager.findFragmentByTag("fragmentTag");
                    if (fragment != null) {
                        ((MessageFragment) fragment).refresh();
                    }
                    mShPreferencesUtil.setHomeRedMessage(false);
                } else {
                    showNewLabel();
                }
            }
        }

    }
	 /**
     * 判断是否显示消息红点——new
     */
    private void showNewLabel() {
        // 判断是否登录
        if (mShPreferencesUtil.getLoginState()
                && mShPreferencesUtil.getHomeRedMessage()
                && fragmentManager.findFragmentByTag("fragmentTag") != indexFragment) {
        	image_message_point.setVisibility(View.VISIBLE);
        } else {
        	image_message_point.setVisibility(View.GONE);
            /*if (fragmentManager.findFragmentByTag("fragmentTag")  == messageFragment) {
            	mShPreferencesUtil.setHomeRedMessage(false);
            }*/
        }
    }
}
